var EventMgr = require("event_manager");

var WEBSOCKET_URL = "ws://192.168.1.161:8027/apiwebd/webSocketServer.do";

cc.Class({
    extends: cc.Component,

    properties: {
        websocket: null,
    },

    onLoad: function () {
        var self = this;
        this.websocket = new WebSocket(WEBSOCKET_URL);
        this.websocket.onopen = function (event) {self.onWebSocketConnected(event);};
        this.websocket.onmessage = function (event) {self.onWebSocketMessage(event);};
        this.websocket.onclose = function (event) {self.onWebSocketClosed(event);};
        this.websocket.onerror = function (event) {self.onWebSocketError(event);};

        cc.game.addPersistRootNode(this.node);
    },
    
    //链接WebSocket成功
    onWebSocketConnected: function (event) {
        cc.log("event = " + event);
    },
    
    //接受WebSocket信息
    onWebSocketMessage: function (event) {
        cc.log("event = " + event);
        var data = JSON.parse(event.data);
        switch (data.pid) {
            case 1000:
                EventMgr.trigger("socket_login", [data]);
                break;
            case 1001:
                EventMgr.trigger("socket_createroom", [data]);
                break;
            case 1002:
                EventMgr.trigger("socket_enterroom", [data]);
                break;
                
        }
        
    },
    
    //关闭WebSocket成功
    onWebSocketClosed: function (event) {
        cc.log("event = " + event);
    },
    
    //WebSocket出错
    onWebSocketError: function (event) {
        cc.log("event = " + event);
    },
});
